home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 17543 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.2 KB  |  75 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: casting w/ virtual base classes
  5. Date: Tue, 16 Apr 1996 14:47:41 +0200
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <317396ED.ABD322C@intellektik.informatik.th-darmstadt.de>
  8. References: <31728499.6201DD56@unisql.com>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. Ed Hill wrote:
  16. > I have the following class hierarchy
  17. > class Derived : public virtual Base {...};
  18. > Suppose there is a function foo that returns a pointer to a virtual
  19. > base class.
  20. >         Base* foo(void) {...}
  21. > Now, in my program I have a variable declared as a pointer to Derived.
  22. >         int main() {
  23. >                 Derived *dp;
  24. >                 ...
  25. >                 exit 0;
  26. >         }
  27. > Book Explanation:
  28. > =================
  29. > In a virtual derivation, the derived class object contains the derived
  30. > part and a pointer to the virtual base part. The virtual base class is
  31. > not contained within the derived class object.
  32. > ==================
  33. > My compiler does not allow either of the two following statements:
  34. >         Derived *dp1 = foo();
  35. >         Derived *dp2 = (Derived *) foo();
  36. > error: cast: Base* ->derived dp2*; Base is virtual base
  37. > Ok, fine...
  38. > However, the following compiles:
  39. >         Derived *dp = (Derived *) (void *) foo();
  40. > Then, I'm able to access members of Derived and get correct data,
  41. > remember foo() returns a pointer to a virtual base.
  42. >         dp->num; // for example
  43. > ===
  44. > Q1: Is the double cast legal? Why? / Why not?
  45.  
  46. It's legal -- but the result is undefined.
  47. The forthcoming C++ standard provides a special cast-operator
  48. for this purpose. The 'dynamic_cast'
  49.  
  50.     Derived* dp=dyanmic_cast<Derived*>(foo());
  51.  
  52. will safely narrow the pointer (*). If the returned object
  53. is not an object of a subclass of 'Dervived', the dynamic_cast
  54. expression returns a null-pointer.
  55.  
  56.     Enno
  57.  
  58. (*) Base should have at least one virtual function, e.g. the dtor.
  59.